/**
 * Copyright (C) 2009 Fsti Inc.
 *
 */
package com.fsti.ppmw.port.payment;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.lang.Validate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 * 支付接口信息DAO实现类
 * 
 * @author Song Qing
 *
 */
public class PaymentDAOImpl implements PaymentDAO {

	private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@SuppressWarnings("unchecked")
	public Payment select(String requestId) {
		Validate.notEmpty(requestId);

		String query = "SELECT * FROM t_auto_payinterface WHERE requestid=?";
		return (Payment) jdbcTemplate.queryForObject(query, new Object[] { Long.valueOf(requestId) }, new RowMapper() {
			public Object mapRow(ResultSet resultSet, int rowNum) throws SQLException {
				Payment payment = new Payment();
				payment.setAreaCode(resultSet.getString("areacode"));
				payment.setFlowNo(resultSet.getString("flowno"));
				payment.setInfoStatus(String.valueOf(resultSet.getInt("infostatus")));
				payment.setOrderFee(resultSet.getString("orderfee"));
				payment.setOrderId(resultSet.getString("orderid"));
				payment.setBalance(resultSet.getString("balance"));
				payment.setOrderStatus(resultSet.getString("orderstatus"));
				payment.setRequestId(String.valueOf(resultSet.getLong("requestid")));
				payment.setRequestType(String.valueOf(resultSet.getInt("requesttype")));
				payment.setRespCode(resultSet.getString("resp_code"));
				payment.setTimestamp(resultSet.getTime("timestamp"));
				payment.setUserTel(resultSet.getString("usertel"));
				return payment;
			}
		});
	}

	public void update(Payment payment) {
		StringBuilder sql = new StringBuilder("UPDATE t_auto_payinterface SET");
		sql.append(" orderid='").append(payment.getOrderId()).append("',");
		sql.append(" balance='").append(payment.getBalance()).append("',");
		sql.append(" orderfee='").append(payment.getOrderFee()).append("',");
		sql.append(" orderstatus='").append(payment.getOrderStatus()).append("',");
		sql.append(" resp_code='").append(payment.getRespCode()).append("',");
		sql.append(" infostatus=2 ").append("WHERE requestid=").append(Long.valueOf(payment.getRequestId()));
		jdbcTemplate.update(sql.toString());
	}

}
